import 'package:flutter/material.dart';

class SafeBuilder extends StatelessWidget {
  final Widget Function(BuildContext) builder;

  const SafeBuilder({Key? key, required this.builder}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    try {
      return builder(context);
    } catch (e, stack) {
      debugPrint('构建错误: $e');
      debugPrint('堆栈: $stack');

      // 返回一个错误显示小部件而不是崩溃
      return Center(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Icon(Icons.error_outline, color: Colors.red, size: 48),
              const SizedBox(height: 16),
              Text('出现了一个错误', style: Theme.of(context).textTheme.titleLarge),
              const SizedBox(height: 8),
              Text(e.toString(), style: Theme.of(context).textTheme.bodyMedium),
            ],
          ),
        ),
      );
    }
  }
}
